﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BUS;
using DTO; 


namespace GUI
{
    public partial class uc_HoaDonBanHang : DevExpress.XtraEditors.XtraUserControl
    {
        public uc_HoaDonBanHang()
        {
            InitializeComponent();
        }

        private MobileBL mobileBL = new MobileBL();
        private AccessoryBL accessBL = new AccessoryBL();
        private WarrantyBL warrantyBL = new WarrantyBL();
        List<MobileDTO> ListMobile = new List<MobileDTO>();
        List<AccesoryDTO> ListAccess = new List<AccesoryDTO>();
        DataTable dt = new DataTable();
        SellAccessoryDetailBL sellaccdetailBl = new SellAccessoryDetailBL();
        SellMobileDetailBL sellmobiledetailBl = new SellMobileDetailBL();
        SellGoodsBL sellgoodBl = new SellGoodsBL();
        List<SellAccessoryDetailDTO> ListAccessoryDetail = new List<SellAccessoryDetailDTO>();
        List<SellMobileDetailDTO> ListMobileDetail = new List<SellMobileDetailDTO>();
        CustomerDTO customerdto = new CustomerDTO();
        CustomerBL cusbll = new CustomerBL();
        private void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Xác Nhận Thanh Toán?", "Confirmation", MessageBoxButtons.YesNo) ==
               DialogResult.Yes)
                {
                    if (txtHoTen.Text.Length < 2 || txtDate.Text == "" || int.Parse(txtTongTien.Text) == 0)
                    {
                        MessageBox.Show("Thiếu thông tin phiếu hàng, yêu cầu kiểm tra lại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    } 
                    else
                    {
                        if (chbKhachHangCu.Checked == false)
                    {
                        customerdto.Name = txtHoTen.Text;
                        customerdto.Phone = txtSDT.Text;
                        customerdto.Address = txtDiaChi.Text;
                        cusbll.Customer_Insert(customerdto);
                    }
                    List<CustomerDTO> listcus = new List<CustomerDTO>();
                    listcus = cusbll.Custummer_SelectByName(txtHoTen.Text);
                    customerdto = listcus[listcus.Count - 1];
                    foreach (MobileDTO mobile in ListMobile)
                    {
                        mobileBL.Mobile_Insert_1(mobile.MobileID, mobile.Count);

                    }
                    foreach (AccesoryDTO acc in ListAccess)
                    {
                        accessBL.Accessory_Update(acc);
                    }
                    SellGoodsDTO sellgoodDTO = new SellGoodsDTO();
                    sellgoodDTO.AccountID = UserAccount.getUser().getUserID();
                    sellgoodDTO.CustomerID = customerdto.CustomerID;
                    sellgoodDTO.Date = txtDate.DateTime;
                    sellgoodDTO.TotalSellCost = int.Parse(txtTongTien.Text);
                    sellgoodBl.SellGoods_Insert(sellgoodDTO);
                    sellgoodDTO = sellgoodBl.SellGoods_SelectALL()[sellgoodBl.SellGoods_SelectALL().Count - 1];
                    for (int i = 0; i < gridView1.RowCount; ++i)
                    {
                        String s = gridView1.GetRowCellValue(i, gridView1.Columns[4]).ToString();
                        if (s == "Điện Thoại")
                        {
                            SellMobileDetailDTO dto = new SellMobileDetailDTO();
                            dto.SellID = sellgoodDTO.SellID;
                            dto.MobileID = int.Parse(gridView1.GetRowCellValue(i, gridView1.Columns[0]).ToString());
                            dto.Number = int.Parse(gridView1.GetRowCellValue(i, gridView1.Columns[2]).ToString());
                            sellmobiledetailBl.SellMobileDetail_Insert(dto);
                            dto = sellmobiledetailBl.SellMobileDetail_SelectALL()[sellmobiledetailBl.SellMobileDetail_SelectALL().Count - 1];
                            WarrantyDTO warranty = new WarrantyDTO();
                            warranty.SellMobileID = dto.SellMobileID;
                            foreach (MobileDTO mobile in ListMobile)
                            {
                                warranty.Endday = txtDate.DateTime.AddDays(mobile.WarrantyTime);
                                warrantyBL.Warranty_Insert(warranty);
                            }
                        }
                        else if (s == "Phụ Kiện")
                        {
                            SellAccessoryDetailDTO dto = new SellAccessoryDetailDTO();
                            dto.SellId = sellgoodDTO.SellID;
                            dto.AccessoryId = int.Parse(gridView1.GetRowCellValue(i, gridView1.Columns[0]).ToString());
                            dto.Number = int.Parse(gridView1.GetRowCellValue(i, gridView1.Columns[2]).ToString());
                            sellaccdetailBl.SellAccessoryDetail_Insert(dto);
                        }
                    }
                    txtTongTien.Text = "";
                    MessageBox.Show("Lưu hóa đơn thành công", "Confirmation", MessageBoxButtons.OK);
                    }
                    
                }

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Lưu hóa đơn không thành công", "Confirmation", MessageBoxButtons.OK);
                return;
            }
              
            
           

        }

        private void txtMaHang_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            Constraint.checkLenght(txtMaHang, e, 3);
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                if (cbLoaiHang.SelectedIndex == 0)
                {
                    MobileDTO mobile = mobileBL.Mobile_SelectByID(int.Parse(txtMaHang.Text));
                    txtTenHang.Text = mobile.Name;
                    txtNhanHieu.Text = mobile.Brand;
                    txtTinhTrang.Text = mobile.State;
                    txtSoLuongTon.Text = mobile.Count.ToString();
                    txtDonGiaBan.Text = ((int)(mobile.Prize)).ToString();
                }
                else if (cbLoaiHang.SelectedIndex == 1)
                {
                    AccesoryDTO accessory = new AccesoryDTO();
                    accessory = accessBL.Accessory_SelectByID(int.Parse(txtMaHang.Text));
                    txtTenHang.Text = accessory.Name;
                    txtNhanHieu.Text = accessory.Brand;
                    txtTinhTrang.Text = "";
                    txtSoLuongTon.Text = accessory.Count.ToString();
                    txtDonGiaBan.Text = accessory.Prize.ToString();
                }
                else
                    MessageBox.Show("Yêu cầu chọn loại hàng trước", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void txtSoLuongBan_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
                e.Handled = true;
            Constraint.checkLenght(txtSoLuongBan, e, 2);
            Constraint.checkLenght(txtSDT, e, 11);
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            if (int.Parse(txtSoLuongBan.Text) == 0)
                MessageBox.Show("Nhập số lượng bán!");
            else if(txtTenHang.Text == "")
            {
                MessageBox.Show("Yêu cầu chọn hàng");
            }
            else
            {

                if (cbLoaiHang.SelectedIndex == 0)
                {
                    MobileDTO mobile = mobileBL.Mobile_SelectByID(int.Parse(txtMaHang.Text));
                    mobile.Count -= int.Parse(txtSoLuongBan.Text);
                    ListMobile.Add(mobile);
                }
                else
                {
                    AccesoryDTO acc = accessBL.Accessory_SelectByID(int.Parse(txtMaHang.Text));
                    acc.Count -= int.Parse(txtSoLuongBan.Text);
                    ListAccess.Add(acc);
                }
                DataRow dr = dt.NewRow();
                dr.BeginEdit();
                dr["ID"] = txtMaHang.Text;
                dr["Prize"] = txtDonGiaBan.Text;
                dr["Number"] = txtSoLuongBan.Text;
                dr["Sum"] = (int.Parse(txtDonGiaBan.Text) * int.Parse(txtSoLuongBan.Text)).ToString();
                dr["Type"] = cbLoaiHang.Text;
                dr.EndEdit();
                dt.Rows.Add(dr);
                int tongtien;
                tongtien = int.Parse(txtSoLuongBan.Text) * int.Parse(txtDonGiaBan.Text);
                if (txtTongTien.Text != "")
                    txtTongTien.Text = (tongtien + int.Parse(txtTongTien.Text)).ToString();
                else
                    txtTongTien.Text = tongtien.ToString();
                txtMaHang.Text = "";
                txtNhanHieu.Text = "";
                txtTenHang.Text = "";
                txtSoLuongBan.Text = "0";
                txtSoLuongTon.Text = "0";
                txtDonGiaBan.Text = "0";
                txtTinhTrang.Text = "0";
            
            }
        }

        private void uc_HoaDonBanHang_Load(object sender, EventArgs e)
        {
            dt.Columns.Add("ID");
            dt.Columns.Add("Prize");
            dt.Columns.Add("Number");
            dt.Columns.Add("Sum");
            dt.Columns.Add("Type");
            gridPhieuBan.DataSource = dt;
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (txtMaHang.Text == "" || txtNhanHieu.Text == "" || txtSoLuongTon.Text == "" || txtTenHang.Text == "")
            {
                MessageBox.Show("Yêu cầu chọn mặt hàng");
            }
            else
            {
                if (MessageBox.Show("Xác nhận xóa mặt hàng này từ hóa đơn?", "Confirmation", MessageBoxButtons.YesNo) ==
              DialogResult.Yes)
                {
                    try
                    {
                        int id = int.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[0]).ToString());
                        string type = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[4]).ToString();
                        txtTongTien.Text = (int.Parse(txtTongTien.Text) - int.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[3]).ToString())).ToString();
                        if (type == "Điện Thoại")
                        {
                            foreach (MobileDTO mobile in ListMobile)
                            {
                                if (mobile.MobileID == id)
                                {
                                    ListMobile.Remove(mobile);
                                    break;
                                }
                            }
                        }
                        else if (type == "Phụ Kiện")
                        {
                            foreach (AccesoryDTO acc in ListAccess)
                            {
                                if (acc.AccessoryID == id)
                                {
                                    ListAccess.Remove(acc);
                                    break;
                                }
                            }
                        }
                        dt.Rows.RemoveAt(gridView1.FocusedRowHandle);
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Có lỗi xảy ra khi thực thi", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    }
                        
                 }
               
            }
        }

        private void chbKhachHangCu_CheckedChanged(object sender, EventArgs e)
        {
            if (chbKhachHangCu.Checked)
            {
                txtMaKH.Enabled = true;
                txtHoTen.Enabled = false;
                txtDiaChi.Enabled = false;
                txtSDT.Enabled = false;
            }
            else
            {
                txtMaKH.Enabled = false;
                txtHoTen.Enabled = true;
                txtDiaChi.Enabled = true;
                txtSDT.Enabled = true;
            }
        }

        private void txtMaKH_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (txtMaKH.Text != "")
            {
                customerdto = cusbll.Custummer_SelectByID(int.Parse(txtMaKH.Text));
                txtHoTen.Text = customerdto.Name;
                txtSDT.Text = customerdto.Phone;
                txtDiaChi.Text = customerdto.Address;
            }
        }

        private void groupControl2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void txtHoTen_KeyPress(object sender, KeyPressEventArgs e)
        {
            Constraint.checkLenght(txtHoTen, e, 100);
            Constraint.checkLenght(txtDiaChi, e, 150);
        }
    }
}
